package com.feeyo.nfc;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.util.Log;

/**
 * Created by zzw on 2017/3/1.
 */

public class NfcUtil {
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private Activity mActivity;

    public NfcUtil(Activity activity) {
        mActivity = activity;
        mAdapter = NfcAdapter.getDefaultAdapter(activity);
        //拦截系统级的NFC扫描，例如扫描蓝牙
        mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity,
                activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE);
    }

    public long getNfcId(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
            return getDec(id);
        }
        return 0;
    }

    public String getNfcIdHex(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
            String hex = UtilExtension.bytesToHexString(id);
            Log.e("NFC", "原始十六进制：" + hex);
            return hex;
        }
        return "";
    }

    private long getDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    public void onResume() {
        if (mAdapter != null && mAdapter.isEnabled()) {
            mAdapter.enableForegroundDispatch(mActivity, mPendingIntent, null, null);
        }
    }

    public void onPause() {
        if (mAdapter != null) {
            //隐式启动
            mAdapter.disableForegroundDispatch(mActivity);
        }
    }
}
